import NativeNoteTrails from 'rtn-supernote-plugin-core/src/module/NativeNoteTrails';
import StickerDataSQL from '../db';
import {DB_ST} from './DBFields';
import Suffix from './suffix';
import suffix from './suffix';
import NativeFileUtils from 'rtn-supernote-plugin-core/src/module/NativeFileUtils';
import NativePluginManager from 'rtn-supernote-plugin-core/src/module/NativePluginManager';
import {findNext2Em, findNextEm, splitBySecondLastSlash} from './jsUtils';
import {unzip} from 'react-native-zip-archive';
import NativeStickerUtils from 'react-native-sticker-lib/src/NativeStickerUtils';
import Constant from './Constant';
import RNFS from 'react-native-fs';

/*
 *添加贴纸库
 * */
export const stickerGroupAdd = async (groupName, fm = null, createTime = null) => {
  const num = Date.now();
  let dir_name = 'sticker_group_' + num;
  const pluginPath = await NativePluginManager.getPluginDirPath();
  const subDirPath = pluginPath + '/sticker/' + dir_name;
  let name = groupName;
  name = await renameFunGroup(groupName, DB_ST.SELECT_STICKER_GROUP_LIKE_ST, fm);
  const time = createTime ? createTime : Date.now();
  console.log("stickerGroupAdd time:" + time + "==" + createTime);
  const { code, data, results } = await StickerDataSQL.db_fun(
    DB_ST.ADD_STICKER_GROUP_ST,
    [name, num, subDirPath, dir_name, time, time],
  );
  console.log(data, 'addDataaddDataaddDataaddData');
  return {
    code,
    data: {
      name,
      num,
      path: subDirPath,
      dir_name,
      id: results?.insertId,
      create_time: time,
      update_time: time,
    },
  };
};

/*
 * 添加导入的贴纸
 * */
export const saveExportSticker = async (sticker, stickerGroup) => {
  let path = sticker?.path,
    thumbPath = sticker?.path
      .replace('/sticker/', '/thumbnail/')
      .replace(sticker.name + suffix.sticker, Date.now() + suffix.png);

  console.log("saveExportSticker path", path, thumbPath, sticker, stickerGroup);
  const name = sticker?.name;
  // const name = await renameFun(sticker?.name, DB_ST.SELECT_STICKER_LIKE_ST);
  // 贴纸名改过，需要对贴纸路径也重命名
  if (name !== sticker?.name) {
    let newPath = path.substring(0, path.lastIndexOf('/')) + "/"+name + suffix.sticker;
    await NativeFileUtils.renameToFile(path, newPath);
    path = newPath;
  }

  return await saveStickerDB(path, thumbPath, name, stickerGroup);
};

/*
 * 添加贴纸
 * */
export const saveSticker = async (sticker, stickerName) => {
  try {
    // 名字为空
    if (!stickerName.trim()) {
      return;
    }
    // 是否有相同的贴纸
/*     const {code, data} = await StickerDataSQL.db_fun(DB_ST.SELECT_NAME_ST, [
      stickerName,
    ]);
    console.log(data, '是否有相同的贴纸');
    if (data?.length > 0) {
      return;
    } */
    // 贴纸路径、缩略图路径
    let stickerPath = sticker.path + '/' + stickerName + Suffix.sticker;
    const thumbPath = (sticker.path + '/' + Date.now() + Suffix.png).replace(
      '/sticker/',
      '/thumbnail/',
    );
    // 保存贴纸到本地
    const re = await NativeNoteTrails.saveSticker(stickerPath);
    // 保存成功
    if (re) {
      return await saveStickerDB(stickerPath, thumbPath, stickerName, sticker);
    }
  } catch (e) {
    console.error(e, 'saveSticker');
  }
};
/*
 * 保存贴纸到数据库
 * */
export const saveStickerDB = async (
  stickerPath,
  thumbPath,
  stickerName,
  sticker,
) => {
  try {
    let md5 = await NativeFileUtils.getFileMD5(stickerPath);
    let date = Date.now();
    let args = [
      stickerName,
      stickerPath,
      thumbPath,
      sticker.id,
      date,
      date,
      0,
      0,
      md5,
    ];
    const {code, data} = await StickerDataSQL.db_fun(
      DB_ST.ADD_STICKER_ST,
      args,
    );
    if (code === 200) {
      await _thumbnailGroup(thumbPath, stickerPath);
      await StickerDataSQL.db_fun(DB_ST.UPDATE_GROUP_STICKER_THUMB_ST, [
        thumbPath,
        sticker?.id,
      ]);
      return true;
    }
  } catch (e) {
    console.log(e, 'saveStickerDB');
  }
};

/*
 * 保存缩略图到本地
 * */
export const _thumbnailGroup = async (thumbPath, stickerPath) => {
  try {
    console.log(thumbPath, stickerPath, 'thumbPath, stickerPath');
    const stickSize = await NativeNoteTrails.getStickerSize(stickerPath);
    console.log(stickSize, 'stickSizestickSize');
    return await NativeNoteTrails.generateStickerThumbnail(
      stickerPath,
      thumbPath,
      stickSize.width,
      stickSize.height,
    );
  } catch (e) {
    console.log(e, '_thumbnailGroup');
  }
};

/*
 * 移动贴纸
 * */
export const moveSticker = async (item, obj, oldObj) => {
  try {
    // 贴纸移动到目标库，可能有重复名字，需要重命名
    let newStickerName = await renameSticker(item?.name,
      DB_ST.SELECT_STICKER_LIKE_ST_BY_GROUP_ID,
      obj.id
    );
    let path = splitBySecondLastSlash(item?.path, obj.dir_name);
    if(newStickerName !== item.name) {
      path =  path.substring(0, path.lastIndexOf('/')) + "/"+newStickerName + suffix.sticker;
    }
    let thumb_sticker = splitBySecondLastSlash(
      item.thumb_sticker,
      obj.dir_name,
    );
    const re = await NativeFileUtils.copyFile(item.path, path);
    console.log(re, 'NativeFileUtils.copyFile');
    if (re) {
      await _thumbnailGroup(thumb_sticker, path);
      let res = await StickerDataSQL.db_fun(DB_ST.UPDATE_STICKER_MOVE_ST, [
        newStickerName,
        path,
        thumb_sticker,
        obj?.id,
        Date.now(),
        item?.id,
      ]);
      console.log(res, 'moveSticker');
      if (res?.code === 200) {
        await NativeFileUtils.deleteFile(item.path);
        await NativeFileUtils.deleteFile(item.thumb_sticker);
        await StickerDataSQL.db_fun(DB_ST.UPDATE_GROUP_STICKER_THUMB_ST, [
          thumb_sticker,
          obj?.id,
        ]);
        await thumbToUse(oldObj);
        return {code: 200, data: item};
      } else {
        return false;
      }
    }
  } catch (e) {
    console.log(e, 'moveStickermoveSticker');
  }
};

/*
 * 导入贴纸库
 * */
export const importSticker = async (item, taskMap, taskId, callback, createTime = null) => {
  try {
    var exists = await RNFS.exists(item?.path);
    // 文件不存在
    if(!exists) {
      const result = {code: 500};
      return result;
    }
    var re = await NativeStickerUtils.checkStickerZip(item?.path);
    if (!re) {
      const result = {code: 400};
      return result;
    }
    // 导入被取消了
    if (taskMap.get(taskId)) {
      return {code: 300};
    }
    let obj = {};
    const res = await stickerGroupAdd(item?.name, 1, createTime);
    obj = res.data;
    const unzipRes = await unzip(item?.path, obj?.path, 'UTF-8');
    // 导入被取消了
    if (taskMap.get(taskId)) {
      await delStickerGroup(
        [obj?.id],
        DB_ST.DELETE_GROUP_STICKERS_ST,
        obj,
        true,
      );
      await NativeFileUtils.deleteDir(obj?.path);
      return {code: 300};
    }
    let fileResArr = [];
    if (unzipRes === obj?.path) {
      fileResArr = await NativeFileUtils.listFiles(unzipRes);
      if (
        fileResArr?.filter(item => item?.path?.indexOf(suffix.sticker) < 0)
          ?.length > 0
      ) {
        await delStickerGroup(
          [obj?.id],
          DB_ST.DELETE_GROUP_STICKERS_ST,
          obj,
          true,
        );
        return {code: 400};
      }
      if (fileResArr?.length > 200) {
        fileResArr = fileResArr.slice(0, 200);
        fileResArr.slice(200)?.map(async item => {
          await NativeFileUtils.deleteFile(item?.path);
        });
      }
      let i = 0;
      let lastSaveDBTime = Date.now();
      for (const fileItem of fileResArr) {
        // 导入被取消了
        if (taskMap.get(taskId)) {
          await delStickerGroup(
            [obj?.id],
            DB_ST.DELETE_GROUP_STICKERS_ST,
            obj,
            true,
          );
          return {code: 300};
        }
        let sticker = {
          path: fileItem?.path,
          name: fileItem?.path.replace(/.*\//, '').replace(/\.[^\.]*$/, ''),
        };
        await saveExportSticker(sticker, obj);
        i++;
        if(Date.now() - lastSaveDBTime >= 1000
          || i == fileResArr.length) 
        {
          lastSaveDBTime = Date.now();
          callback(i / fileResArr.length);
        }
        
      }
      return {code: 200, data: obj, list: fileResArr};
    }
  } catch (e) {
    console.log(e, 'EXPORT/plugin_sticker.snplg');
  }
};

const cutName = (name) => {
  return name?.length > Constant.maxInputNum
    ? name.slice(0, Constant.maxInputNum)
    : name;
}

/*
 * 重命名，规避当前名称
 * */
export const renameWithoutIDFun = async (name, id, db, fm = null) => {
  try {
    let nm = fm === 1 ? name.match(/^([^()]+)/)[1] : name;
    nm = cutName(nm);
    let arr = [];
    if (fm) {
      let {code, data} = await StickerDataSQL.db_fun(db, [`${nm}%`, id]);
      arr = data;
    } else {
      let {code, data} = await StickerDataSQL.db_fun(db, [`${nm}%`, id]);
      arr = data;
    }
    console.log(arr, 'newNamenewName');
    let newName = nm;
    if(arr?.length > 0) {
      if(!arr.some(item => item.name === newName)) {
        return newName;
      }
      for(let i = 1; i <= 10000; i++) {
        var tailStr = "("+ i+ ")";
        newName = nm + tailStr;
        // 新的字符串太长，截取字符串
        if (newName.length > Constant.maxInputNum) {
          var cutLength = 1;
          return renameWithoutIDFun(
            nm.slice(0, nm.length - cutLength),
            id,
            db,
            fm);
        }
        if(!arr.some(item => item.name === newName)) {
          return newName;
        }
      }
    }
    console.log(newName, 'newNamenewName');
    return newName;
  } catch (e) {}
};

// 重名贴纸
export const renameSticker = async (name, db, groupId, stickerId = null) =>{
  try {
    // 对字符串进行截取，不能超过150个字符
    var baseName = cutName(name);
    const {code, data} = await StickerDataSQL.db_fun(db, [`${baseName}%`, groupId]);
    console.log("renameSticker data", data);
    let arr = data.filter(item => item?.id !== stickerId);
    console.log("renameSticker arr", arr);
    console.log("renameSticker name", baseName);

    let newName = baseName;

    if(arr?.length > 0) {
      if(!arr.some(item => item.name === newName)) {
        return newName;
      }

      for(let i = 1; i <= 10000; i++) {
        var tailStr = "("+ i+ ")";
        newName = baseName + tailStr;
        
        // 新的字符串太长，截取字符串
        if (newName.length > Constant.maxInputNum) {
          var cutLength = 1;
          return renameSticker(
            baseName.slice(0, baseName.length - cutLength),
            db,
            groupId,
            stickerId);
        }
        
        if(!arr.some(item => item.name === newName)) {
          return newName;
        }
      }
    }
    return newName;
  }catch (e) {
    console.error("renameSticker", e);
  }

}

/*
 * 重命名
 * */
export const renameFunGroup = async (name, db, fm = null) => {
  try {
    let nm = fm === 1 ? name.match(/^([^()]+)/)[1] : name;
    nm = cutName(nm);
    let arr = [];
    if (fm) {
      let {code, data} = await StickerDataSQL.db_fun(db, [`${nm}%`]);
      arr = data;
      // 检查内置贴纸是否重名
      var defaultData = await StickerDataSQL.db_default_fun(db, [`${nm}%`]);
      if (defaultData.data?.length > 0) {
        arr = [...arr, ...defaultData.data];
      }
    } else {
      let {code, data} = await StickerDataSQL.db_fun(db, [`${nm}%`]);
      arr = data;
      
    }
    console.log(arr, 'newNamenewName');
    let newName = nm;
    if(arr?.length > 0) {
      if(!arr.some(item => item.name === newName)) {
        return newName;
      }
      for(let i = 1; i <= 10000; i++) {
        var tailStr = "("+ i+ ")";
        newName = nm + tailStr;
        // 新的字符串太长，截取字符串
        if (newName.length > Constant.maxInputNum) {
          var cutLength = 1;
          return renameFunGroup(
            nm.slice(0, nm.length - cutLength),
            db,
            fm);
        }
        if(!arr.some(item => item.name === newName)) {
          return newName;
        }
      }
    }
    
    console.log(newName, 'newNamenewName');
    return newName;
  } catch (e) {}
};

/*
 * 删除贴纸库
 * */
export const delStickerGroup = async (ids, db, obj, ty) => {
  let db_st = ty ? DB_ST.SELECT_STICKER_ST : DB_ST.SELECT_GROUP_ID_ST;
  await NativeFileUtils.deleteDir(obj?.path);
  await NativeFileUtils.deleteDir(
    obj?.path.replace('/sticker/', '/thumbnail/'),
  );
  const res = await StickerDataSQL.db_fun(db_st, ids);
  let idList = [];
  res?.data?.map(item => {
    idList.push(item?.id);
  });
  console.log(idList, 'idListidListidList');
  const {code} = await StickerDataSQL.db_del(DB_ST.DELETE_STICKERS_ST, idList);
  if (code === 200) {
    return await StickerDataSQL.db_del(db, ids);
  }
};
/*
 * 删除贴纸
 * */
export const delSticker = async (ids, db, obj, list, ty, callback) => {
  let lastDelTime = Date.now();
  list.map(async (item, index) => {
    await NativeFileUtils.deleteFile(item?.path);
    await NativeFileUtils.deleteFile(item?.thumb_sticker);
    // if (Date.now() - lastDelTime >= 1000 || index + 1 === list.length) {
    //   lastDelTime = Date.now();
    //   callback((index + 1) / list.length);
    // }
  });
  await StickerDataSQL.db_del(db, ids);
  return await thumbToUse(obj);
};
export const thumbToUse = async obj => {
  const {code, data} = await StickerDataSQL.db_fun(DB_ST.SELECT_STICKER_ST, [
    obj?.id,
  ]);
  let path = data?.length > 0 ? data[0]?.thumb_sticker : null;
  return await StickerDataSQL.db_fun(DB_ST.UPDATE_GROUP_STICKER_THUMB_ST, [
    path,
    obj?.id,
  ]);
};
